<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="商品名称" prop="spActiveName" >
        <el-input
          v-model="queryParams.spActiveName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 200px;"
        />
      </el-form-item>
      <el-form-item label="是否上架" prop="spIsGrounding">
        <el-select v-model="queryParams.spIsGrounding" placeholder="请选择上架" clearable style="width: 200px;">
          <el-option
            v-for="dict in dict.type.shop_active_top"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['shop:active:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:active:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:active:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['shop:active:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          size="mini"
          plain
          type="primary"
          icon="el-icon-edit"
          @click="handNormsList"
        >商品规格</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activeListByTop" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品id" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="spActiveName" />
      <el-table-column label="商品图片" align="center" prop="spImage" >
        <template slot-scope="scope">
          <image-preview :src="scope.row.spImage" :width="50" :height="50"/>
        </template>
      </el-table-column>

      <el-table-column label="商品类型" align="center" prop="typeName" />
      <el-table-column label="商品库存(个)" align="center" prop="spAllNum" />
      <el-table-column label="销量(个)" align="center" prop="spSaleNum" />
      <!--     点击上架可以切换-->
      <el-table-column label="上架" align="center" prop="spIsGrounding">
        <template slot-scope="scope">
          <span @click="toggleActiveStatus(scope.row)">
            <dict-tag :options="dict.type.shop_active_top" :value="scope.row.spIsGrounding" />
          </span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="350px">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.spIsNorms === '1'"
            size="small"
            type="primary"
            icon="el-icon-edit"
            @click="handNormsByActive(scope.row)"
          >商品规格</el-button>
          <el-button
            size="small"
            type="warning"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['shop:active:edit']"
          >修改</el-button>
          <el-button
            size="small"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['shop:active:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>



    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息列表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品名称" prop="spActiveName">
              <el-input v-model="form.spActiveName" placeholder="请输入商品名称" style="width: 250px"/>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品类型" prop="spTypeCode">
              <div style="width: 250px;height: 35px;border: 1px solid #cccccc;
                border-radius: 5px;
                float: left;text-align: center" @click="toggleTreeVisible">{{typeName}}</div>
              <el-dialog :visible.sync="treeVisible" width="300px" append-to-body>
                <el-tree
                  :data="treeData"
                  :props="defaultProps"
                  node-key="typeCode"
                  @node-click="handleNodeClick"
                  :highlight-current="true"
                  :show-checkbox="false"
                  default-expand-all>
                </el-tree>
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="商品销量" prop="spSaleNum">
              <el-input v-model="form.spSaleNum" placeholder="请输入销量" style="width: 250px"/>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="是否上架" prop="spIsGrounding">
              <el-select v-model="form.spIsGrounding" placeholder="请选择上架" style="width: 250px">
                <el-option
                  v-for="dict in dict.type.shop_active_top"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <!--          TODO 如果是添加，就显示那个商品规格按钮-->
          <el-col :span="10">
            <el-form-item label="商品规格" prop="spIsNorms">
              <el-select v-model="form.spIsNorms" placeholder="请选择是否添加商品规格" style="width: 250px">
                <el-option
                  v-for="dict in dict.type.shop_active_top"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-form-item label="商品图片" prop="spImage">
          <image-upload v-model="form.spImage"/>
        </el-form-item>

        <el-form-item label="总库存" prop="spAllNum">
          <el-input v-model="form.spAllNum" placeholder="请输入商品总库存" style="width: 250px"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="更改上架状态"
      :visible.sync="dialogVisible"
      width="30%"
      @close="handleClose">
      <span>确定要更改此商品的上架状态吗？</span>
      <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="confirmChangeStatus">确 定</el-button>
            </span>
    </el-dialog>

    <el-dialog
      title="启用状态"
      :visible.sync="dialogVisibleStart"
      width="30%"
      @close="handleClose">
      <span>确定要更改此商品的状态为启用吗？</span>
      <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisibleStart = false">取 消</el-button>
              <el-button type="primary" @click="confirmStart">确 定</el-button>
            </span>
    </el-dialog>

    <el-dialog
      title="禁言状态"
      :visible.sync="dialogVisibleNoStart"
      width="30%"
      @close="handleClose">
      <span>确定要更改此商品的状态为禁用吗？</span>
      <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisibleNoStart = false">取 消</el-button>
              <el-button type="primary" @click="confirmNoStart">确 定</el-button>
            </span>
    </el-dialog>

    <el-dialog
      title="确认删除"
      :visible.sync="dialogConfirmDelete"
      width="30%"
      @close="handleClose">
      <span>确定要删除该商品规格及商品规格值吗？</span>
      <span slot="footer" class="dialog-footer">
              <el-button @click="dialogConfirmDelete = false">取 消</el-button>
              <el-button type="primary" @click="confirmDeleteNorms">确 定</el-button>
            </span>
    </el-dialog>
    <!--    -------------------------------------------------------------------------------------------------------------->

    <el-dialog title="商品规格" :visible.sync="openNormsAfterInfo" width="800px" append-to-body>
      <span>商品规格设置<el-button @click="handleNormsInfo"
                                   style="margin-left: 20px;">添加商品新规格信息</el-button></span>
      <el-table v-loading="loading" :data="normsList" @selection-change="handleSelectionChange">
        <el-table-column label="产品规格" align="center" prop="spNormsName" />
        <!--        TODO 规格list-->
        <el-table-column label="规格值" align="center" prop="spNormsValues" />

        <el-table-column label="启用" align="center" prop="spNormsStart" >
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.spNormsStart === '1' ? '已启用' : '未启用'" placement="top">
              <el-button size="mini" type="text" @click="handleStatusChange(scope.row)">
                {{ scope.row.spNormsStart === '1' ? '禁用' : '启用' }}
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdateValue(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleNormsAfterDelete(scope.row)"
            >删除</el-button>

          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!------------------------------ 添加或修改商品规格对话框 ---------------------------------------->
    <el-dialog title="添加商品规格" :visible.sync="openNormsValue" width="800px" append-to-body>
      <el-form ref="formNorms" :model="formNorms" :rules="rules" label-width="80px">
        <el-form-item label="规格名称" prop="spNormsName">
          <el-input v-model="formNorms.spNormsName" placeholder="请输入规格名称" style="width: 250px"/>
        </el-form-item>
        <span>规格值:<el-button @click="handleAddNormsValue" style="margin-left: 20px">添加规格值</el-button></span>
        <el-table v-loading="loading" :data="normsValueList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="规格值" align="center" prop="spNormsValue" />

          <el-table-column label="规格图片" align="center" prop="spNormsImages" >
            <template slot-scope="scope">
              <image-preview :src="scope.row.spNormsImages" :width="50" :height="50"/>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">

              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteValue(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitNormsList">确 定</el-button>
        <el-button @click="cancelNormsList">取 消</el-button>
      </div>
    </el-dialog>

    <!--    ------------------------------------添加商品规格信息---------------------------------------->
    <el-dialog title="添加规格信息" :visible.sync="openAddNormsValue" width="500px" append-to-body>
      <el-form ref="formValue" :model="formValue" :rules="rules" label-width="80px">
        <el-form-item label="规格值" prop="spNormsValue">
          <el-input v-model="formValue.spNormsValue" placeholder="请输入规格值" />
        </el-form-item>
        <el-form-item label="规格图片" prop="spNormsImages">
          <image-upload v-model="formValue.spNormsImages"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitNormsValue">确 定</el-button>
        <el-button @click="cancelNormsValue">取 消</el-button>
      </div>
    </el-dialog>


    <!--    修改商品规格------------------------------------->
    <el-dialog title="修改商品规格" :visible.sync="openNormsUpdate" width="800px" append-to-body>
      <el-form ref="formNorms" :model="formNormsUpdate" :rules="rules" label-width="80px">
        <el-form-item label="规格名称" prop="spNormsName">
          <el-input v-model="formNormsUpdate.spNormsName" placeholder="请输入规格名称" style="width: 250px"/>
        </el-form-item>
        <span><strong>规格值:</strong></span>
        <el-table v-loading="loading" :data="normsValueUpdateList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="规格值" align="center" prop="spNormsValue" />

          <el-table-column label="规格图片" align="center" prop="spNormsImages" >
            <template slot-scope="scope">
              <image-preview :src="scope.row.spNormsImages" :width="50" :height="50"/>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdateNorms(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteUpdate(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitNormsUpdate">确 定</el-button>
        <el-button @click="cancelNormsUpdate">取 消</el-button>
      </div>
    </el-dialog>

    <!--    ------------------------------------修改规格信息---------------------------------------->
    <el-dialog title="修改规格信息" :visible.sync="openUpdateNormsValue" width="500px" append-to-body>
      <el-form ref="formValue" :model="formUpdateValue" :rules="rules" label-width="80px">
        <el-form-item label="规格值" prop="spNormsValue">
          <el-input v-model="formUpdateValue.spNormsValue" placeholder="请输入规格值" />
        </el-form-item>
        <el-form-item label="规格图片" prop="spNormsImages">
          <image-upload v-model="formUpdateValue.spNormsImages"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpdateValue">确 定</el-button>
        <el-button @click="cancelUpdateValue">取 消</el-button>
      </div>
    </el-dialog>
    <!--  TODO-------------------------------------------------------------------------------------------------------------------->
    <el-dialog title="规格信息" :visible.sync="openNormInfoByActive" width="700px" append-to-body>
      <span>产品规格设置<el-button @click="handleChangeNoms" style="margin-left: 20px">选择该商品需要的规格</el-button></span>
      <div style="background-color: #f1f1f1;margin-top: 10px;margin-bottom: 30px;width: auto;height: auto;">
        <el-checkbox-group v-model="checkedNorms" @change="handleCheckedNormsChange">
          <el-checkbox
            v-for="norm in normValues"
            :label="norm.spNormsValue"
            :key="norm.id">
            {{ norm.spNormsValue }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <span>按规格设置</span>
      <div style="width: auto;height: auto;background-color: #f1f1f1;margin-top: 10px;margin-bottom: 20px">
        <el-checkbox v-model="showNormsPrice" label="商品价格" ></el-checkbox>
        <el-checkbox v-model="showNormsNum" label="商品库存" ></el-checkbox>
        <el-checkbox v-model="showNormsWeight" label="规格重量" ></el-checkbox>
      </div>

      <el-table :data="normDetailInfo" style="width: 100%;margin-bottom: 20px">
        <el-table-column prop="spNormsValue" label="商品规格" width="150" style="text-align: center"></el-table-column>
        <el-table-column v-if="showNormsPrice" label="商品价格" width="150" style="text-align: center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.spNormsPrice" placeholder="请输入商品价格"></el-input>
          </template>
        </el-table-column>
        <el-table-column v-if="showNormsNum" label="商品库存" width="150" style="text-align: center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.spNormsNum" placeholder="请输入商品库存"></el-input>
          </template>
        </el-table-column>
        <el-table-column v-if="showNormsWeight" label="规格重量(kg)" width="150" style="text-align: center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.spNormsWeight" placeholder="请输入规格重量(kg)"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <span>总共{{checkedNorms.length}}个</span>
      <div style="margin-top: 40px;margin-left: 200px">
        <el-button type="primary" @click="submitUpdateNormsValue">确 定</el-button>
        <el-button @click="cancelUpdateNormsValue">取 消</el-button>
      </div>

    </el-dialog>

    <el-dialog title="商品规格" :visible.sync="openNormsChooseInfo" width="800px" append-to-body>
      <el-table v-loading="loading" :data="normsChooseList" @selection-change="handleSelectionChange">

        <el-table-column label="产品规格" align="center" prop="spNormsName" />
        <el-table-column label="规格值" align="center" prop="spNormsValues" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-thumb"
              @click="handleNormsConfirm(scope.row)"
            >确认使用</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import {
  listActive,
  getActive,
  delActive,
  addActive,
  updateActive,
  updateTopStatus,
  getTopStatusList
} from '@/api/shop/active'
import { listHouse } from '@/api/shop/house'
import {
  addShopNormsInfo,
  deleteNormsValue,
  getNormsUpdateById,
  getShopNormsInfoByAll,
  updateNormsById,
  updateNoStart,
  updateStart
} from '@/api/shop/normsAfter'
import { selectTreeType } from '@/api/shop/typeArticle'
import {
  confirmUseInfo,
  getAllNormAndOtherList,
  getNormsByActiveId,
  updateNormsOtherInfo
} from '@/api/shop/shopNormsOther'
import Vue from 'vue'
export default {
  name: "Active",
  dicts: ['shop_active_top','shop_sale_way','shop_product_specifications','shop_norms_use'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      dialogVisible: false,//确认上架状态
      dialogVisibleStart:false,//启用
      dialogVisibleNoStart:false,//禁用
      openNormsAfterInfo:false,//商品规格信息
      openUpdateNormsValue:false,
      openNormsChooseInfo:false,
      openNormsValue:false,
      openAddNormsValue:false,
      openNormsUpdate:false,
      openNormInfoByActive:false,
      formNormsUpdate:{},//更新弹窗
      formUpdateValue:{},//更新规格
      normsValueUpdateList:[],//更新表格
      // 总条数

      total: 0,
      // 商品信息列表表格数据
      activeListByTop: [],
      normsValueList:[],//商品规格值列表
      normsList:[],//商品规格列表
      // 弹出层标题
      title: "",
      normsTitle:"",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spActiveName: null,
        spTypeId: null,
        spIsGrounding: null,
      },
      // 表单参数
      form:{},
      formNormsInfo: {},
      formNorms:{},
      formValue:{},
      spActiveTypeList:[],
      spHouseList:[],
      // 表单校验
      rules: {
      },
      typeChoose:{
        id:'',
        topStatus:''
      },
      currentRow:'',
      spActiveId:'',
      treeVisible:false,
      treeData: [],
      defaultProps: {
        children: 'children',  // 修改为与后端数据一致的字段
        label: 'typeName'
      },
      typeName:"",
      selectedParent:null,
      shopActiveId:'',//商品id
      normsUpdate:{},
      dialogConfirmDelete:false,
      shopNormsId:'',//商品规格id
      normsUpdateId:'',
      checkAll: false,
      checkedNorms: [],
      selectCheckedNorms:[],
      normValues: [],
      isIndeterminate: true,
      normsChooseList:[],
      showNormsPrice:false,
      showNormsNum:false,
      showNormsWeight:false,
      normsValueInfo:{},
      normDetailInfo:[]
    };
  },
  watch: {
    checkedNorms(newVal) {
      // 使用 newVal（包含 spNormsValue 的数组）来从 normValues 中检索完整的规格对象
      this.normDetailInfo = newVal.map(spNormsValue => {
        const norm = this.normValues.find(norm => norm.spNormsValue === spNormsValue);
        if (norm) {
          return {
            id: norm.id,
            spNormsValue: norm.spNormsValue,
            spNormsPrice: null,
            spNormsNum: null,
            spNormsWeight: null
          };
        }
        return null;
      }).filter(item => item !== null);

      console.log('----------', this.normDetailInfo);
    },
    'form.parentCode'(newVal, oldVal) {
      this.selectedParent = newVal;
    },
    'selectedParent'(newVal, oldVal) {
      this.form.spTypeCode = newVal;
    }
  },
  mounted() {
    if (this.form && this.form.spTypeCode) {
      this.selectedParent = this.form.spTypeCode;
    }
  },
  created() {
    this.getList();
    this.getHouse();
    this.getTreeSelect();
  },
  methods: {
    /** 查询商品信息列表列表 */
    getList() {
      this.loading = true;
      getTopStatusList(this.queryParams).then(response => {
        this.activeListByTop = response.rows
        this.loading = false
        console.log("上架.......",response)
        // 首先设置total
        this.total = response.rows.length
      })
    },
    //查询仓库列表
    getHouse() {
      listHouse().then(response => {
        if (response && Array.isArray(response.rows) && response.rows.length > 0) {
          this.spHouseList = response.rows.map(item => ({
            id: item.id,
            houseName: item.houseName
          }));
        } else {
          console.error('没有获取到仓库数据');
          this.spHouseList = [];
        }
      })
    },
    //获取类型树
    getTreeSelect() {
      this.loading = true;
      selectTreeType().then(res => {
        this.treeData = res.data;
        console.log(this.treeData)
        this.processTreeData();
        this.loading = false;
      }).catch(error => {
        console.error('加载数据失败:', error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    toggleTreeVisible() {
      this.treeVisible = !this.treeVisible;
    },
    processTreeData() {
      function calculateLevel(nodes, parentCode = 0, level = 1) {
        nodes.forEach(node => {
          node.level = level;
          if (node.childList) {
            calculateLevel(node.childList, node.typeCode, level + 1); // 递归计算子节点的层级
          }
        });
      }

      this.expandedRows = this.treeData.filter(node => !node.parentCode || node.parentCode === 0);
      calculateLevel(this.treeData);
      this.markHasChildren(this.treeData);
    },
    markHasChildren(nodes) {
      nodes.forEach(node => {
        node.hasChildren = node.childList && node.childList.length > 0;
        if (node.childList) {
          this.markHasChildren(node.childList);
        }
      });
    },
    handleNodeClick(data, node, component) {
      this.selectedParent = data.typeCode;
      this.typeName = data.typeName;
      this.form.spTypeCode = this.selectedParent
      this.treeVisible = false; // 关闭对话框
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        spActiveName: null,
        spImage: null,
        spSinglePrice: null,
        spGroupPrice: null,
        spTypeCode: null,
        spInventory: null,
        spSaleNum: null,
        spIsGrounding: null,
        spGroupPeople: null
      };
      this.resetForm("form");
    },
    //重置
    resetNormDetail() {
      this.checkedNorms = []; // 清空选中的规格
      this.normDetailInfo = []; // 清空规格详情表数据
      this.selectCheckedNorms = [];
      this.showNormsPrice = false; // 重置显示控制
      this.showNormsNum = false;
      this.showNormsWeight = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品信息列表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getActive(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品信息列表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateActive(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActive(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品信息列表编号为"' + ids + '"的数据项？').then(function() {
        return delActive(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('shop/active/export', {
        ...this.queryParams
      }, `active_${new Date().getTime()}.xlsx`)
    },
    handleClose() {
      this.dialogVisible = false;
    },
    toggleActiveStatus(row) {
      // console.log(row)
      this.currentRow = row
      this.dialogVisible = true;
    },

    //确认修改
    confirmChangeStatus() {
      const newStatus = this.currentRow.spIsGrounding === '0' ? '1' : '0';
      this.typeChoose.id = this.currentRow.id
      this.typeChoose.topStatus = newStatus
      updateTopStatus(this.typeChoose).then(response => {
        this.dialogVisible = false
        this.getList()
      })
    },

    //   ------------------------------------------
    //   商品规格信息
    handleNormsInfo() {
      this.openNormsValue = true
    },

    //   添加商品规格值信息
    handleAddNormsValue() {
      this.openAddNormsValue = true
    },

    resetNormsValue() {
      this.formValue = {
        spNormsValue: null, //规格值为空
        spNormsImages: null //规格图片为空
      }
    },

    //确认商品规格
    submitNormsValue() {
      //1、把每一次添加商品规格存储起来  normsValueList
      this.normsValueList.push(this.formValue)
      console.log(this.normsValueList)
      //关闭添加商品规格值
      this.openAddNormsValue = false
      this.openNormsAfterInfo = false
      this.getList()
      //2、重置为空
      this.resetNormsValue()
    },

    handleDeleteValue(row) {
      //移除这一行的数据
      const index = this.normsValueList.findIndex(item => item === row);
      if (index > -1) {
        this.normsValueList.splice(index, 1);
      }
    },

    //取消商品规格
    cancelNormsValue() {
      //关闭添加商品规格值
      this.openAddNormsValue = false
    },

    handNormsList(row) {
      console.log(row)
      getShopNormsInfoByAll().then(res => {
        console.log("商品规格信息.............", res.data)
        this.normsList = res.data
        //打开规格信息弹窗
        this.openNormsAfterInfo = true
      }).catch(err => {
        console.error("获取商品规格信息失败:", err)
      })
    },
    cancelNormsList() {
      this.openNormsValue = false
    },
    submitNormsList() {
      this.formNorms = {
        shopNormsValueList: this.normsValueList, //商品规格值列表
        spNormsName: this.formNorms.spNormsName //商品规格名
      };
      addShopNormsInfo(this.formNorms).then(res => {
        console.log(res)
        this.$modal.msgSuccess("添加商品规格成功")
        this.openNormsValue = false
        this.getList()
      })
    },

    //启用/禁言状态变化
    handleStatusChange(row) {
      console.log("-------------------", row)
      this.normsUpdate = {
        id: row.id,
        spNormsStart: row.spNormsStart
      }
      //状态为开启，要关闭的
      if (row.spNormsStart === "1") {
        this.dialogVisibleNoStart = true
      }
      //状态为关闭，要开启的
      if (row.spNormsStart === "0") {
        //打开
        this.dialogVisibleStart = true
      }
    },

    //确认开启
    confirmStart() {
      updateStart(this.normsUpdate).then(res => {
        console.log(res)
        this.dialogVisibleStart = false
        this.openNormsAfterInfo = false
        this.getList()
      })
    },
    //确认关闭
    confirmNoStart() {
      updateNoStart(this.normsUpdate).then(res => {
        console.log(res)
        this.dialogVisibleNoStart = false
        this.openNormsAfterInfo = false
        this.getList()
      })
    },
    handleNormsAfterDelete(row) {
      console.log(row)
      this.shopNormsId = row.id
      this.dialogConfirmDelete = true
    },
    confirmDeleteNorms() {
      deleteNormsValue(this.shopNormsId).then(res => {
        console.log(res)
        this.$modal.msgSuccess("删除商品规格成功")
        this.dialogConfirmDelete = false
      })
    },

    handleUpdateValue(row) {
      console.log('修改', row)
      this.normsUpdateId = row.id
      getNormsUpdateById(row.id).then(res => {
        console.log("......", res.data)
        this.formNormsUpdate.spNormsName = res.data.spNormsName
        this.normsValueUpdateList = res.data.normValueList
      })
      //打开更新弹窗
      this.openNormsUpdate = true
    },

    //确认更新
    submitNormsUpdate() {
      const normUpdate = {
        //商品规格id
        id: this.normsUpdateId,
        //商品规格名
        spNormsName: this.formNormsUpdate.spNormsName,
        //商品规格列表
        normValueList: this.normsValueUpdateList
      }
      updateNormsById(normUpdate).then(res => {
        console.log('更新商品规格', res.data)
        this.openNormsUpdate = false
        this.openNormsAfterInfo = false
        this.getList()
      })

    },
    //取消更新
    cancelNormsUpdate() {
      this.openNormsUpdate = false
      this.openNormsAfterInfo = false
      this.getList()
    },

    //更新弹窗--修改
    handleUpdateNorms(row) {
      console.log(row)
      this.formUpdateValue = row
      this.openUpdateNormsValue = true
    },
    //更新弹窗--删除
    handleDeleteUpdate() {
      //移除这一行的数据
      const index = this.normsValueUpdateList.findIndex(item => item === row);
      if (index > -1) {
        this.normsValueUpdateList.splice(index, 1);
      }
    },

    //确认更新
    submitUpdateValue() {

      this.openUpdateNormsValue = false
    },
    cancelUpdateValue() {
      this.openUpdateNormsValue = false
    },

    submitUpdateNormsValue() {
      console.log("确认........", this.normDetailInfo)
      updateNormsOtherInfo(this.normDetailInfo).then(res => {
        console.log(res)
        this.$modal.msgSuccess("确认成功！")
        this.openNormInfoByActive = false
      })
      this.resetNormDetail()
    },
    cancelUpdateNormsValue() {
      this.openNormInfoByActive = false
      this.resetNormDetail()
    },
    //商品规格（根据商品id）
    handNormsByActive(row) {
      this.shopActiveId = row.id
      this.openNormInfoByActive = true;
      getNormsByActiveId(row.id).then(res => {
        console.log("..................", res.data)
        this.normValues = res.data
      })
    },
    handleChangeNoms() {
      getAllNormAndOtherList().then(res => {
        console.log("商品规格信息.............", res.data)
        this.normsChooseList = res.data
        //打开规格信息弹窗
        this.openNormsChooseInfo = true
      }).catch(err => {
        console.error("获取商品规格信息失败:", err)
      })
    },

    //确认使用
    handleNormsConfirm(row) {
      const normsChoose = {
        spNormsId: row.id,
        spActiveId: this.shopActiveId
      }
      confirmUseInfo(normsChoose).then(res => {
        console.log(res)
        this.$modal.msgSuccess("确认成功")
        this.openNormsChooseInfo = false
        this.openNormInfoByActive = false
        this.getList()
      })
    },
    handleCheckedNormsChange(value) {
      this.checkedNorms = value;
    }
  }
};
</script>
<style scoped>
/* 横向布局的 Form 容器 */
.horizontal-form {
  display: flex;
  flex-direction: column; /* 初始为列布局，但内部项将使用 flex-wrap 实现横向排列 */
  row-gap: 10px; /* 控制行与行之间的间距 */
}

/* 横向排列的 Form Item */
.horizontal-form .el-form-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 使得 label 和 input 都在起始位置对齐 */
  row-gap: 5px; /* label 和 input 之间的间距 */
}

/* 使得 Form Item 内的 label 和 input 横向排列 */
.horizontal-form .el-form-item__label {
  width: 120px; /* 根据你的需求调整标签宽度 */
}

.horizontal-form .el-form-item__content {
  flex: 1; /* 让输入框占据剩余空间 */
}

/* 如果需要，可以进一步调整输入框的样式 */
.horizontal-form .el-input,
.horizontal-form .el-input-number {
  width: 100%; /* 让输入框完全填充可用空间 */
}
</style>
